// upload 控制器
const Controlloer = require('egg').Controller;
const pump = require('mz-modules/pump');
const path = require('path');
const fs = require('fs');

class UploadController extends Controlloer {
  async index() {
    // 管道流
    const stream = await this.ctx.getFileStream();
    // console.log(stream);
    // 设置上传文件名字
    const filename = Date.now() + encodeURIComponent(stream.filename);
    // 写入路径
    const target = path.join('app/public/upload', filename);
    // 写入文件
    const writeStream = fs.createWriteStream(target);
    await pump(stream, writeStream);
    this.ctx.body = {
      filename,
      url: `/upload/${filename}`
    };
  }
}

module.exports = UploadController;
